//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from 'react';
import type { MemoInfo } from "@/api/user_memo";
import { create_memo, update_memo } from "@/api/user_memo";
import { Form, message, Modal, Popover, Select } from 'antd';
import { Compact as CompactPicker } from '@uiw/react-color';
import { useStores } from '@/hooks';
import { change_file_owner, useCommonEditor } from '@/components/Editor';
import { FILE_OWNER_TYPE_NONE, FILE_OWNER_TYPE_USER_MEMO } from '@/api/fs';
import { request } from '@/utils/request';
import { useTranslation } from "react-i18next";

export interface EditMemoModalProps {
    memoInfo?: MemoInfo;
    tagList: string[];
    onCancel: () => void;
    onOk: () => void;
}

const EditMemoModal = (props: EditMemoModalProps) => {
    const { t } = useTranslation();

    const userStore = useStores("userStore");

    const [tagList, setTagList] = useState<string[]>(props.memoInfo?.basic_info.tag_list ?? []);
    const [bgColor, setBgColor] = useState(props.memoInfo?.basic_info.bg_color ?? "#8bc34a");

    const { editor, editorRef } = useCommonEditor({
        placeholder: t("workbench.memo.inputContent"),
        content: props.memoInfo?.basic_info.content ?? "",
        fsId: userStore.userInfo.userMemoFsId,
        ownerType: props.memoInfo == undefined ? FILE_OWNER_TYPE_NONE : FILE_OWNER_TYPE_USER_MEMO,
        ownerId: props.memoInfo == undefined ? "" : props.memoInfo.memo_id,
        historyInToolbar: false,
        clipboardInToolbar: false,
        commonInToolbar: true,
        pubResInToolbar: false,
    });

    const createMemo = async () => {
        const content = editorRef.current?.getContent() ?? { type: "doc" };
        const createRes = await request(create_memo({
            session_id: userStore.sessionId,
            basic_info: {
                content: JSON.stringify(content),
                tag_list: tagList,
                bg_color: bgColor,
            },
        }));
        await change_file_owner(content, userStore.sessionId, FILE_OWNER_TYPE_USER_MEMO, createRes.memo_id);
        message.info(t("text.createSuccess"));
        props.onOk();
    };

    const updateMemo = async () => {
        if (props.memoInfo == undefined) {
            return;
        }
        const content = editorRef.current?.getContent() ?? { type: "doc" };
        await request(update_memo({
            session_id: userStore.sessionId,
            memo_id: props.memoInfo.memo_id,
            basic_info: {
                content: JSON.stringify(content),
                tag_list: tagList,
                bg_color: bgColor,
            },
        }));
        message.info(t("text.updateSuccess"));
        props.onOk();
    };

    return (
        <Modal open title={`${props.memoInfo == undefined ? t("workbench.memo.create") : t("workbench.memo.update")}`} mask={false}
            okText={props.memoInfo == undefined ? t("text.create") : t("text.update")}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.memoInfo == undefined) {
                    createMemo();
                } else {
                    updateMemo();
                }
            }}>
            <Form layout='inline'>
                <Form.Item label={t("workbench.memo.tag")} style={{ flex: 1 }}>
                    <Select mode='tags' value={tagList} onChange={values => setTagList(values.map(value => value.toLocaleLowerCase()))} >
                        {props.tagList.map(tag => (
                            <Select.Option key={tag} value={tag}>{tag}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label={t("workbench.memo.bgColor")}>
                    <Popover trigger="click" placement="bottom" content={
                        <CompactPicker color={bgColor}
                            onChange={value => {
                                setBgColor(value.hex);
                            }} />
                    }>
                        <div style={{ backgroundColor: bgColor, width: "20px", height: "20px", cursor: "pointer" }} />
                    </Popover>
                </Form.Item>
            </Form>
            <div className="_orgPostContext" style={{ marginTop: "10px", backgroundColor: bgColor }}>
                {editor}
            </div>
        </Modal>
    );
};

export default EditMemoModal;